<template>
    <a-modal v-model:visible="visible" title="登录" @cancel="resetFields" :footer="null" >
      <a-form
        :label-col="formLayout.labelCol"
        :wrapper-col="formLayout.wrapperCol"
      >
        <a-form-item label="用户名" v-bind="validateInfos.username">
          <a-input v-model:value="SingModelRef.username" />
        </a-form-item>
        <a-form-item label="密码" v-bind="validateInfos.password">
          <a-input-password  v-model:value="SingModelRef.password" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
          <a-button type="primary" :loading="loading" @click="handleLogin" block shape="round" style="height: 40px;">确认</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
</template>
<script setup>
import  { ref, reactive, toRaw } from 'vue'
import { Form, message } from 'ant-design-vue';
import { useUserStore } from '@/store/modules/user.js'
import {  login } from '@/api/login/index.js'
const userStore = useUserStore()
let loading = ref(false)
let visible = ref(false)
const showSignModal = () => {
  visible.value = true
}
const formLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  }
}
const useForm = Form.useForm;
const rulesRef = reactive({
  username: [
    {
      required: true,
      message: '请填写昵称',
      trigger: 'blur'
    },
  ],
  password: [
    {
      required: true,
      message: '请填写密码',
      trigger: 'blur'
    },
  ]
})
const SingModelRef = reactive({
  username: '',
  password: '',
})

// 登录
const handleLogin = () => {
  validate()
  .then(
    loading.value = true,
    login(toRaw(SingModelRef))
    .then((res) => {
      window.localStorage.setItem('access-token', res.token) // 持久化token
      visible.value = false
      resetFields()
      loading.value = false
      userStore.GetUserInfo() // 登录成功获取用户信息
      return message.success('登录成功')
    })
    .catch(err => {
      message.error(err || '登录失败')
    })
    .finally(() => {
      loading.value = false
    })
  )
  .catch(err => {
    loading.value = false
  })
}

const { resetFields, validate, validateInfos } = useForm(SingModelRef, rulesRef)
// 暴露方法给父组件
defineExpose({
  showSignModal
})
</script>